package net.topicopedia.other;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.labs.repackaged.org.json.JSONArray;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.appengine.labs.repackaged.org.json.JSONObject;

@SuppressWarnings("serial")
public class CreateTopicsServlet extends HttpServlet {
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
		      throws IOException {
		    System.out.println("Creating new todo ");
		    
		    String jsonString = req.getParameter("json");
		    
		    JSONObject jsonObject = null;
			try {
				jsonObject = new JSONObject(jsonString);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			resp.addHeader("Access-Control-Allow-Origin", "*");
			resp.setContentType("text/plain");
			
			JSONArray jsonlist = null;
			try {
				jsonlist = jsonObject.getJSONArray("items");
			} catch (JSONException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			
			if ( jsonlist != null )
			{
				for ( int j=0; j < jsonlist.length(); j++ )
				{
					JSONObject json = null;
					try {
						json = (JSONObject) jsonlist.get(j);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					if ( json != null )
					{
						DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
						
						String uuid = null;
						
						try {
							uuid = (String) json.get("uuid");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						Key topicKey;
						Entity topic = null;
						
						Boolean addToCategory = false;
						
						if ( uuid != null )
						{
							Long id = Long.parseLong(uuid);
							if ( id > 0 )
							{
								topicKey = KeyFactory.createKey("Topic", id );
								try {
									topic = datastore.get(topicKey);
								} catch (EntityNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
						} 
						
						if ( topic == null )
						{
							topic = new Entity("Topic");
							addToCategory = true;
						}
						
						try {
							topic.setProperty("title", json.get("title") );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							topic.setProperty("category", json.get("category") );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							topic.setProperty("descriptor", json.get("descriptor") );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							String tags = (String) json.get("tags");
							List<String> list = Arrays.asList(tags.split(", "));
							
							topic.setProperty("tags", list );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							topic.setProperty("links", json.get("links").toString() );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							topic.setProperty("image", json.get("image") );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						try {
							topic.setProperty("items", json.get("items").toString() );
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
						topicKey = datastore.put( topic );
						
						if ( addToCategory ){
							Key categoryKey;
							try {
								categoryKey = KeyFactory.createKey("Category", Long.parseLong((String) json.get("category") ));
								try {
									Entity category = datastore.get(categoryKey);
									Long count = (Long) category.getProperty("count");
									if ( count != null )
									{
										count++;
									}
									category.setProperty("count", count);
									categoryKey = datastore.put( category );
									
								} catch (EntityNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							} catch (NumberFormatException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							} catch (JSONException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						}
						resp.getWriter().println(String.valueOf( topic.getProperty("title") ));
						resp.getWriter().println(" topic id :: " + topicKey.getId() );
					}
				}
			}
	}

}
 